<!--
 * @Author: early-autumn
 * @Date: 2020-05-14 17:19:23
 * @LastEditors: early-autumn
 * @LastEditTime: 2020-05-23 13:43:59
 -->
<template>
  <div class="app-container">
    <el-tabs type="border-card">
      <el-tab-pane label="医生排班">
        <scheduling-table
          :loading="loading"
          :header-data="doctorList"
          :content-data="planList"
          @change="getListPlan"
          @work="handleWork"
          @rest="handleRest"
        ></scheduling-table>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import dayjs from 'dayjs'
import { listStaff } from '@/api/services/common'
import { addPlans, delPlan, listPlan } from '@/api/services/plan'
import { getThisWeekStartWithEnd } from '@/utils/date'

import SchedulingTable from '@/components/yiya/SchedulingTable'

export default {
  name: 'DoctorWorking',
  components: {
    SchedulingTable,
  },
  data() {
    return {
      loading: true,
      // 起止时间
      currentDate: getThisWeekStartWithEnd(),
      // 医生列表
      doctorList: [],
      // 排班列表
      planList: [],
      // 当前显示周
      currentWeek: [],
    }
  },
  computed: {
    ...mapState({
      clinicId: (state) => state.clinic.clinicId,
    }),
  },
  mounted() {
    this.getListStaff()
  },
  methods: {
    /**
     * 获取医生列表
     */
    async getListStaff() {
      const { data } = await listStaff({
        deptId: +this.clinicId,
        postname: '医生',
      })
      this.doctorList = data.filter(
        (doctor) => doctor.userName !== '未指定医生'
      )
    },
    /**
     * 获取排班信息
     */
    async getListPlan(e) {
      if (e) {
        this.currentWeek = e
      }
      try {
        this.loading = true
        const [start, end] = this.currentWeek
        const { rows } = await listPlan({
          beginTime: dayjs(start).format('YYYY-MM-DD'),
          endTime: dayjs(end).format('YYYY-MM-DD'),
        })
        this.planList = rows
      } finally {
        this.loading = false
      }
    },
    /**
     * 上班
     */
    async handleWork(e) {
      try {
        this.loading = true
        await delPlan(e.join(','))
        await this.getListPlan()
        this.$message.success('排班成功')
      } finally {
        this.loading = false
      }
    },
    /**
     * 休息
     */
    async handleRest(e) {
      try {
        this.loading = true
        await addPlans({ yiyaPlans: e })
        await this.getListPlan()
        this.$message.success('排班成功')
      } finally {
        this.loading = false
      }
    },
  },
}
</script>
